import 'dart:typed_data';

import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:flutterhello/api/api.dart';
import 'package:flutterhello/controller/Controller.dart';
import 'package:flutterhello/my_app.dart';
import 'package:flutterhello/widgets/loading_dialog.dart';
import 'package:flutterhello/widgets/my_toast.dart';
import 'package:get/get.dart' as MyGet;
import 'package:multi_image_picker/multi_image_picker.dart';

class CreateTeamPage extends StatefulWidget {
  @override
  _CreateTeamPageState createState() => _CreateTeamPageState();
}

class _CreateTeamPageState extends State<CreateTeamPage> {
  GlobalKey<FormState> _formKey = new GlobalKey<FormState>();
  List<Asset> images = [];
  String content = "";
  String name = "";
  String _error;

  Future<void> loadAssets() async {
    List<Asset> resultList;
    String error;

    try {
      resultList = await MultiImagePicker.pickImages(
        maxImages: 1,
        enableCamera: true,
      );
    } on Exception catch (e) {
      error = e.toString();
    }

    // If the widget was removed from the tree while the asynchronous platform
    // message was in flight, we want to discard the reply rather than calling
    // setState to update our non-existent appearance.
    if (!mounted) return;

    setState(() {
      images = images + resultList;
      if (error == null) _error = 'No Error Dectected';
      print(_error);
    });
  }

  Widget buildGridView1() {
    if (images.length == 0)
      return GridView.count(
        crossAxisCount: 3,
        children: [
          Row(
            children: [Text('选择头像')],
          ),
          Container(),
          Container(
            height: 120,
            width: 120,
            decoration: BoxDecoration(
              border: Border(
                  left: BorderSide(width: 1, color: Colors.black26),
                  right: BorderSide(width: 1, color: Colors.black26),
                  bottom: BorderSide(width: 1, color: Colors.black26),
                  top: BorderSide(width: 1, color: Colors.black26)),
              borderRadius: BorderRadius.circular(5),
            ),
            child: IconButton(
              icon: Icon(Icons.add),
              onPressed: loadAssets,
            ),
          ),
        ],
      );
    else {
      Asset asset = images[0];
      return GridView.count(
        crossAxisCount: 3,
        crossAxisSpacing: 10,
        mainAxisSpacing: 10,
        children: [
          Row(
            children: [Text('选择头像')],
          ),
          Container(),
          Container(
            width: 300,
            height: 300,
            child: Stack(
              children: [
                Align(
                  alignment: Alignment(0, 0),
                  child: AssetThumb(
                    asset: asset,
                    width: 300,
                    height: 300,
                  ),
                ),
                Align(
                  alignment: Alignment(0.9, -0.9),
                  child: GestureDetector(
                    child: Icon(
                      const IconData(0xe600, fontFamily: "alIcons"),
                      size: 15,
                      color: Colors.blueGrey,
                    ),
                    onTap: () {
                      setState(() {
                        this.images.removeAt(0);
                      });
                    },
                  ),
                )
              ],
            ),
          )
        ],
      );
    }
  }

  @override
  Widget build(BuildContext _context) {
    return Scaffold(
      appBar: PreferredSize(
        child: AppBar(
          title: Text('创建团队'),
          centerTitle: true,
        ),
        preferredSize: Size.fromHeight(50),
      ),
      body: Container(
        margin: EdgeInsets.all(10),
        child: Column(
          children: <Widget>[
            Expanded(
              child: Column(
                children: <Widget>[
                  TextField(
                    cursorColor: Colors.black87,
                    cursorWidth: 0.5,
                    maxLines: 1,
                    maxLength: 10,
                    style: TextStyle(color: Colors.black54, fontSize: 16),
                    scrollPadding: EdgeInsets.all(0),
                    decoration: InputDecoration(
                      contentPadding: EdgeInsets.all(0),
                      hintText: '团队名称',
                      hintStyle: TextStyle(fontSize: 14, color: Colors.black38),
                      border: InputBorder.none,
                    ),
                    onChanged: (value) {
                      this.name = value;
                    },
                  ),
                  Container(
                    height: 70,
                    width: double.infinity,
                    child: TextFormField(
                      cursorColor: Colors.black87,
                      cursorWidth: 0.5,
                      maxLines: 2,
                      maxLength: 30,
                      style: TextStyle(color: Colors.black54, fontSize: 16),
                      scrollPadding: EdgeInsets.all(0),
                      decoration: InputDecoration(
                          contentPadding: EdgeInsets.all(0),
                          hintText: '团队简介',
                          hintStyle:
                              TextStyle(fontSize: 14, color: Colors.black26),
                          border: InputBorder.none),
                      onSaved: (val) {
                        this.content = val;
                      },
                    ),
                  ),
                  SizedBox(
                    height: 20,
                  ),
                  Expanded(
                    child: Padding(
                      padding: EdgeInsets.only(top: 10),
                      child: buildGridView1(),
                    ),
                  ),
                  Align(
                    alignment: Alignment(0.8, 0),
                    child: GestureDetector(
                        child: Container(
                          height: 50,
                          width: double.infinity,
                          decoration: BoxDecoration(
                            color: Colors.blueGrey,
                            borderRadius: BorderRadius.all(Radius.circular(5)),
                          ),
                          child: Center(
                            child: Text(
                              '提 交',
                              style:
                                  TextStyle(color: Colors.white, fontSize: 20),
                            ),
                          ),
                        ),
                        onTap: () async {
                          var result = await showDialog(
                              context: context,
                              builder: (context) {
                                return AlertDialog(
                                  title: Text('提示'),
                                  content: Text('确认创建吗？'),
                                  actions: <Widget>[
                                    TextButton(
                                      child: Text('取消'),
                                      onPressed: () {
                                        Navigator.of(context).pop('cancel');
                                      },
                                    ),
                                    TextButton(
                                      child: Text('确认'),
                                      onPressed: () {
                                        Navigator.of(context).pop('ok');
                                        submit(this.images, this.name,
                                            this.content, _context);
                                      },
                                    ),
                                  ],
                                );
                              });
                          print('$result');
                        }),
                  )
                ],
              ),
            ),
          ],
        ),
      ),
    );
  }
}

void submit(images, name, content, context) async {
  if (name != "" && images.length != 0) {
    showDialog(
      context: context,
      barrierDismissible: false,
      builder: (BuildContext context) {
        return new LoadingDialog(
          text: "上传中…",
        );
      },
    );
    FormData formData = new FormData.fromMap({});
    for (int i = 0; i < images.length; i++) {
      ByteData byteData = await images[i].getByteData();
      List<int> imageData = byteData.buffer.asUint8List();
      MultipartFile multipartFile = MultipartFile.fromBytes(
        imageData,
        filename: images[i].name,
      );
      formData.files.addAll([
        MapEntry("file", multipartFile),
      ]);
    }
    var res = await Api.uploadImg(formData);
    if (res['code'] == 1000) {
      var res2 = await Api.createTeam({
        "favicon": res['data'][0],
        "introduction": content,
        "groupname": name
      });
      if (res2['code'] == 1000) {
        Navigator.of(context).pop();
        MyTost.showTost(res2['message']);
        MyGet.Get.offAll(MyApp());
      }
    } else {
      MyTost.showTost('上传失败');
      Navigator.of(context).pop();
    }
  } else {
    MyTost.showTost('名称和头像必填');
  }
}
